import {
  Component,
  OnInit,
  ElementRef, AfterViewInit, Input, ViewChild,
} from '@angular/core';
import {CouponService} from '../coupon.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {Router} from "@angular/router";
import {adSystemApiUrl} from "../../../../config/api";

import { Subscription } from "rxjs/Subscription";
import { Observable } from "rxjs/Observable";

export interface  KtCircleCanvas {
  x?: number;
  y?: number;
  radius?: number;
  title?: string;
  content?: string;
  fillColor?: string;
}

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
  providers: [CouponService]
})
export class ListComponent implements OnInit {

  cardList = [];  // 卡券列表
  coupon_name: string; // 卡券名称
  selectedIndex = 0;
  typeIndex = 0;   // 新人礼券 0  支付礼券 1
  typeName = '新人礼品券';

  cardModalVisible = false;
  receiveCardInfo = {UUID: '', cardListByTag: [], allCardList: [], checkedCards: []};  // 领取卡券信息
  checkedTableCards = [];  // 还未确定的选中的卡券
  status = null; // 卡券状态  0: 正常 1: 自己关闭 2: 管理员关闭

  page = 1;
  pageSize = 10;
  total;
  loading = false;

  /* 添加卡券弹窗参数 */
  allChecked = false;
  indeterminate = false;
  addTag_page = 1;
  addTag_pageSize = 7;
  addTag_total;
  addTag_loading = false;
  flag = true;

  //二维码
  qrcodeVisible = false;
  qrcodeShowStatus = false;
  editId = '';
  cardLoading = false;
  editIndex = null;
  editImage = '';
  dataURL = '';

  constructor(private couponService: CouponService,
              private _message: NzMessageService,
              private localStorageService: LocalStorageService,
              private confirmServ: NzModalService,
              private router: Router,
              private ele: ElementRef
  ) {
  }

  ngOnInit() {
    this.judgeCouponStatus();
  }

  handleOk(e) {
    this.qrcodeVisible = false;
  }

  handleCancel(e) {
    this.qrcodeVisible = false;
  }

  copyLink(v) {
    let ele = this.ele.nativeElement.querySelector('#link');
    this.copyToClipboard(ele,v);
  }

  copyToClipboard(oElement, value) {
    let aux = document.createElement("input");
    if (oElement) {
      var content = oElement.innerHTML || oElement.value;
    }
    let _content = value || content;
    aux.setAttribute("value", _content);
    document.body.appendChild(aux);
    aux.select();
    let result = document.execCommand("Copy");
    if(result) {
      this._message.create('success','复制链接成功');
      document.body.removeChild(aux);
    }
  }

  getBase64(url) {
    return new Promise((resolve, reject) => {
      let Img = new Image(),
        dataURL = '';
      Img.setAttribute('crossOrigin', 'anonymous');
      Img.src = url + '?' + new Date().getTime();
      let self = this;
      Img.onload = function () { //要先确保图片完整获取到，这是个异步事件
        let canvas = document.createElement("canvas"), //创建canvas元素
          width = Img.width, //确保canvas的尺寸和图片一样
          height = Img.height;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
        dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
        self.dataURL = dataURL;
        resolve(dataURL);
      };
    });
  }

  downloadImage(src) {
    this.getBase64(src).then(url => {
      let url1 = url;
      let a = document.createElement('a');
      let event = new MouseEvent('click');
      a.href = url1 + '';
      a.download = name || '优惠券图片';
      a.dispatchEvent(event);
    })
  }

  //生成二维码modal
  showQrcodeModal(id, idx) {
    this.editId = id;
    this.editIndex = idx;
    console.log(this.editIndex);
    this.qrcodeVisible = true;
    if (!this.cardList[idx]['editImage']) {
      this.createCoupon();
    }
  }

  createCoupon() {
    this.cardLoading = true;
    this.couponService.createCoupon({'id': this.editId}).subscribe(res => {
      if (res.code === 2000) {
        let flag = false;
        this.getCouponImage().then(data => {
          this.cardList[this.editIndex]['editImage'] = data['data'];
          // this.editImage = data['data'];
          this.cardLoading = false;
          flag = true;
        });
        setTimeout(() => {
          if (!flag) {
            this.getCouponImage().then(data1 => {
              this.cardList[this.editIndex]['editImage'] = data1['data'];
              // this.editImage = data1['data'];
              this.cardLoading = false;
            });
          }
        }, 1000);
      }
    })
  }

  //获取二维码
  getCouponImage() {
    return new Promise((resolve, reject) => {
      this.couponService.getCouponImage({'id': this.editId}).subscribe(res => {
        if (res.code === 200) {
          resolve(res);
        } else {
          reject(res);
          // this.cardLoading = false;
        }
      })
    })
  }

  // 判断商户的卡券开通状态
  judgeCouponStatus() {
    this.couponService.getAppletInfo().subscribe(res => {
      this.localStorageService.setNowApplet(res.data);
      const applet = this.localStorageService.getNowApplet();
      this.status = null;
      let couponExist = false;
      if (!applet.applet_extend.length) {
        this.status = 1;
      } else {
        applet.applet_extend.every((val, idx, array) => {
          if (val.type === 1) {
            couponExist = true;
            if (val.status === 1) {
              this.status = 0;
              this.getListDate();
              this.getGettingList();
            } else {
              this.status = 1;
            }
            return false;
          }
          if (!couponExist) {
            this.status = 1;
          }
          return true;
        });
      }
    });
  }

  showShadow() {
    this.qrcodeShowStatus = true;
  }

  hideShadow() {
    this.qrcodeShowStatus = false;
  }

  // 获取所有卡券列表
  getListDate() {
    this.loading = true;
    this.couponService.getCouponList(this.page, this.pageSize, this.coupon_name).subscribe(res => {
      this.loading = false;
      this.total = res.data.total;
      this.cardList = res.data.data;
      this.cardList.forEach((e, i) => {
        e['editImage'] = '';
      });
      console.log(this.cardList);
      if (!!res.data.data.length) {
        this.dealDate(res.data.data);
      }
    });
  }

  // 处理数据，获取剩余库存量
  dealDate(date) {
    date.every((val, idx, array) => {
      if (val.in_stock_type === 1 && !!val.card_coupons_used_report) {
        val.remain = val.in_stock - val.card_coupons_used_report.used_total;
      } else {
        val.remain = '不限';
      }
      return true;
    });
  }

  goAddPage() {
    if (this.flag) {
      this.router.navigate(['member/coupon/add']);
      this.flag = false;
    }
  }

  goDetail(id) {
    if (this.flag) {
      this.router.navigate(['member/coupon/detail/' + id]);
      this.flag = false;
    }
  }

  goEdit(id) {
    if (this.flag) {
      this.router.navigate(['member/coupon/edit/' + id]);
      this.flag = false;
    }
  }

  // 搜索
  search() {
    this.page = 1;
    this.getListDate();
  }

  // 删除卡券
  delCard(id) {
    const _this = this;
    this.confirmServ.confirm({
      title: '您是否确认要删除此卡券',
      content: '',
      onOk() {
        _this.couponService.delCoupon(id).subscribe(res => {
          if (res.code === 2000) {
            _this._message.create('success', `卡券删除成功`);
            _this.page = 1;
            _this.getListDate();
          } else {
            _this._message.create('error', res.message);
          }
        });
      },
      onCancel() {
      }
    });
  }

  /* 卡券领取设置 */

  // 获取领取设置中的列表
  getGettingList() {
    this.couponService.getTagList(this.typeName).subscribe(res => {
      this.receiveCardInfo.UUID = res.data[0].card_coupons_tag_uuid;
      if (!this.receiveCardInfo.UUID) {
        this._message.create('error', '卡券未包含此Tag,请联系管理员进行添加');
        return;
      }
      return this.couponService.getCouponListByTag(this.receiveCardInfo.UUID).subscribe(rs => {
        if (rs.code === 2000) {
          this.receiveCardInfo.cardListByTag = rs.data.data;
          this.receiveCardInfo.checkedCards = [];
          if (!!rs.data.data.length) {
            this.dealDate(rs.data.data);
            rs.data.data.every((val, idx, array) => {
              this.receiveCardInfo.checkedCards.push(val.card_coupons_uuid);
              return true;
            });
          }
        } else {
          this._message.create('error', rs.message);
        }
      });
    });
  }

  // 删除卡券Tag
  delCardTag(card_coupons_uuid) {
    const _this = this;
    this.confirmServ.confirm({
      title: '您是否确认要删除此卡券',
      content: '',
      onOk() {
        _this.couponService.delCardTag(card_coupons_uuid, _this.receiveCardInfo.UUID).subscribe(res => {
          if (res.code === 2000) {
            _this._message.create('success', `卡券删除成功`);
            if (_this.typeIndex === 0) {
              _this.getGettingList();
            } else {
              _this.getGettingList();
            }
          } else {
            _this._message.create('error', res.message);
          }
        });
      },
      onCancel() {
      }
    });
  }

  pageChange() {
    this.getListDate();
  }

  // 选中领取卡券列表
  selectTab() {
    if (this.typeIndex === 0) {
      this.typeName = '新人礼品券';
      this.getGettingList();
    } else {
      this.typeName = '支付完成卡券';
      this.getGettingList();
    }
  }

  // 添加卡券，绑定tag
  addBindCoupon() {
    this.addTag_page = 1;
    this.checkedTableCards = JSON.parse(JSON.stringify(this.receiveCardInfo.checkedCards));
    this.cardModalVisible = true;
    this.getCradListForTag();
  }

  // 点击添加卡券，获取所有卡券列表
  getCradListForTag() {
    this.addTag_loading = true;
    this.couponService.getCouponList(this.addTag_page, this.addTag_pageSize, '').subscribe(res => {
      this.addTag_loading = false;
      this.addTag_total = res.data.total;
      this.receiveCardInfo.allCardList = res.data.data;
      if (!!res.data.data.length) {
        this.dealDate(res.data.data);
        res.data.data.every((val, idx, array) => {
          val.checked = false;
          if (!!this.checkedTableCards.length) {
            this.checkedTableCards.every((val1, idx1, array1) => {
              if (val.card_coupons_uuid === val1) {
                val.checked = true;
                return false;
              }
              return true;
            });
          }
          return true;
        });
      }
      this.refreshStatus();
    });
  }

  checkedSingle(event: any, data: any) {
    data.checked = event;
    if (event) {
      this.checkedTableCards.push(data.card_coupons_uuid);
    } else {
      this.checkedTableCards.every((val, idx, array) => {
        if (data.card_coupons_uuid === val) {
          this.checkedTableCards.splice(idx, 1);
          return false;
        }
        return true;
      });
    }
    this.refreshStatus();
  }

  checkAll(value) {
    if (value) {
      this.receiveCardInfo.allCardList.every((val, idx, array) => {
        if (!val.checked) {
          val.checked = true;
          this.checkedTableCards.push(val.card_coupons_uuid);
        }
        return true;
      });
    } else {
      this.receiveCardInfo.allCardList.every((val, idx, array) => {
        if (val.checked) {
          val.checked = false;
          this.checkedTableCards.every((val1, idx1, array1) => {
            if (val.card_coupons_uuid === val1) {
              this.checkedTableCards.splice(idx1, 1);
              return false;
            }
            return true;
          });
        }
        return true;
      });
    }
    this.refreshStatus();
  }

  refreshStatus() {
    const allChecked = this.receiveCardInfo.allCardList.every(value => value.checked === true);
    const allUnChecked = this.receiveCardInfo.allCardList.every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  // 批量绑定卡券
  bindingCardByTag() {
    if (this.checkedTableCards.length > 5) {
      this._message.create('info', `最多只能选择五张卡券`);
      return;
    }
    this.couponService.batchCardBinding(this.receiveCardInfo.UUID, this.checkedTableCards).subscribe(res => {
      if (res.code === 2000) {
        this._message.create('success', `卡券绑定成功`);
        this.cardModalVisible = false;
        this.getGettingList();
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  // 申请开通卡券
  applyCoupon() {
    const applet = this.localStorageService.getNowApplet();
    this.couponService.applyCoupon(applet.nick_name, applet.applet_uuid).subscribe(res => {
      if (res.code === 2000) {
        this.judgeCouponStatus();
      } else {
        this._message.create('error', res.message);
      }
    });
  }
}
